<template>
    <div class="app-container">
        <el-form :model="queryParams"
                 ref="queryForm"
                 :inline="true"
                 v-show="showSearch"
                 label-width="80px"
        >
            <el-form-item label="电表编号" prop="sn">
                <el-input
                    v-model="queryParams.sn"
                    placeholder="请输入电表编号"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
            </el-col>
<!--            <el-col :span="1.5">-->
<!--                <el-button-->
<!--                    plain-->
<!--                    size="mini"-->
<!--                    @click="handleTransfer"-->
<!--                >转移电表-->
<!--                </el-button>-->
<!--            </el-col>-->
        </el-row>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>

        <el-checkbox-group v-model="sns" @change="changeCheckboxGroups">

            <el-row v-show="electricityList.length>0" v-loading="loading" :gutter="20"
                    style="margin-top: 10px;font-size: 15px"
                    type="flex" justify="space-around"
                    v-for="(item,index) in electricityList" :key="index"
            >
                <el-col :xl="24">
                    <el-card shadow="always">
                        <div slot="header" class="clearfix"
                             style="display: flex;align-items: center;justify-content: space-between"
                        >
                            <div style="display: flex;align-items: center;width: 80%;">
                                <el-checkbox style="font-size: 14px;color: #abb2bf;" :label="item.sn"/>
                            </div>
                            <div style="width: 10%;">
                                <el-button
                                    type="text"
                                    @click="handleUpdate(item)"
                                >修改
                                </el-button>
                            </div>
                        </div>
                        <div style="display: flex;align-items: center;color: #717783">
                            <span>剩余电量(度)：</span>
                            <span>{{ item.surplus }}</span>
                        </div>
                        <div style="display: flex;align-items: center;color: #717783">
                            <span>表显数(度)：</span>
                            <span>{{ item.totalElectricity }}</span>
                        </div>
                        <div style="display: flex;align-items: center;color: #717783">
                            <span>总电量(度)：</span>
                            <span>{{ (item.totalElectricity + item.virtualTotal).toFixed(2) }}</span>
                        </div>
                        <div style="display: flex;align-items: center;color: #717783">
                            <span>电表状态：</span>
                            <dict-tag :options="dict.type.biz_electricity_status" :value="item.status"/>
                        </div>
                        <div style="display: flex;align-items: center;color: #717783">
                            <span>电表模式：</span>
                            <dict-tag :options="dict.type.biz_electricity_mode" :value="item.electricMeterMode"/>
                        </div>
                        <div style="display: flex;align-items: center;color: #717783">
                            <span>是否在线：</span>
                            <dict-tag :options="dict.type.biz_device_online" :value="item.online"/>
                        </div>
                        <div style="display: flex;align-items: center;color: #717783">
                            <span>创建时间：</span>
                            <span>{{ parseTime(item.createTime) }}</span>
                        </div>

                        <div style="margin-top: 10px;display: flex;justify-content: space-around;align-items: center">
                            <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(item)"
                                v-hasPermi="['business:gateway:remove']"
                            >删除
                            </el-button>
                            <el-dropdown size="mini" @command="(command) => handleCommand(command, item)"
                            >
                                <span class="el-dropdown-link">更多</span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item command="handleReading">抄表</el-dropdown-item>
                                    <el-dropdown-item command="handleSwitchStatus" v-if="item.switchStatus === '0'"
                                                      style="color:sandybrown"
                                    >强制拉闸
                                    </el-dropdown-item>
                                    <el-dropdown-item command="handleSwitchStatus" v-if="item.switchStatus === '1'"
                                                      style="color:#67c23a"
                                    >解除拉闸
                                    </el-dropdown-item>
                                    <el-dropdown-item command="handleSchedule">定时</el-dropdown-item>
                                    <el-dropdown-item command="handlePay">充值</el-dropdown-item>
                                    <el-dropdown-item command="handleDetail">明细</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-checkbox-group>


        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改流量卡信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
                <el-form-item label="电表名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入电表名称"/>
                </el-form-item>

                <el-form-item label="电表编号" prop="sn">
                    <el-input v-model="form.sn" placeholder="请输入电表编号"/>
                </el-form-item>

                <el-form-item label="电表单价" prop="unitPrice">
                    <el-input v-model="form.unitPrice" placeholder="请输入电表单价"/>
                </el-form-item>

                <el-form-item label="欠费停电" prop="oweStop">
                    <el-select v-model="form.oweStop">
                        <el-option
                            v-for="item in dict.type.biz_owe_stop"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="请选择电表状态">
                        <el-option
                            v-for="item in dict.type.biz_electricity_status"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>


                <el-form-item label="电表模式" prop="electricMeterMode">
                    <el-select v-model="form.electricMeterMode" placeholder="请选择电表模式">
                        <el-option
                            v-for="item in dict.type.biz_electricity_mode"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="电表型号" prop="electricMeterMode">
                    <el-select v-model="form.deviceModelId" placeholder="请选择电表模式" filterable>
                        <el-option
                            v-for="item in deviceModelList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
                <el-button size="small" @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!--        定时任务-->
        <ScheduleForm ref="scheduleDig" @success="getList"></ScheduleForm>
        <PayForm ref="payDig" @success="getList"></PayForm>
        <TransferForm ref="transferDig" @success="getList"></TransferForm>
    </div>
</template>

<script>

import {
    addElectricity,
    listElectricity,
    updateElectricity,
    delElectricity,
    getElectricity,
    readingElectricMeter,
    forceoffElectricMeter
} from '@/api/equipment/electricity'
import { listElectricityModelSelect } from '@/api/business/gatewayModel'
import { genUUID } from '@/utils/ruoyi'
import ScheduleForm from '@/views/equipment/electricity/dialog/ScheduleForm.vue'
import PayForm from '@/views/equipment/electricity/dialog/PayForm.vue'
import TransferForm from '@/views/equipment/electricity/dialog/TransferForm.vue'

export default {
    name: 'electricity',
    components: {
        ScheduleForm,
        PayForm,
        TransferForm
    },
    dicts: ['biz_electricity_status', 'biz_electricity_mode', 'biz_owe_stop', 'biz_device_online'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 信息表格数据
            electricityList: [],
            // 电表型号列表
            deviceModelList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                id: null,
                name: null,
                sn: null,
                unitPrice: null,
                sort: null,
                status: null,
                oweStop: null,
                deviceModelId: null,
                electricMeterMode: null
            },
            // 表单参数
            form: {},
            webClientId: genUUID(),
            // 超时时间实例
            timer: null,
            // 判断是否打开连接
            isOpen: false,
            //心跳定时器实例
            heartTime: null,
            // 定义控制是否是第一次点击抄表或者拉闸
            isFirstHandle: false,
            // 定义连接的状态
            readyStatus: 0,
            // websocket 实例
            websocket: null,
            // socket地址
            socketUrl: '',
            // 心跳次数
            socketHeart: 0,
            // 心跳超时时间
            HeartTimeOut: 30000,
            // 错误次数
            socketError: 0,
            // 提示信息
            text: '',
            // 表单校验
            rules: {},
            sns: []
        }
    },
    created() {
        this.getList()
        this.getDeviceModelList()
    },
    methods: {
        changeCheckboxGroups(val) {
            console.log('val', val)
            this.multiple = !val.length
        },
        getList() {
            this.loading = true
            listElectricity(this.queryParams).then(response => {
                this.electricityList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        // 获取电表型号
        getDeviceModelList() {
            listElectricityModelSelect().then(res => {
                console.log(res)
                this.deviceModelList = res.data
            })
        },
        cancel() {
            this.open = false
            this.reset()
        },

        reset() {
            this.form = {
                id: null,
                name: null,
                sn: null,
                unitPrice: null,
                status: null,
                oweStop: null,
                sort: null,
                deviceModelId: null,
                electricMeterMode: null
            }
            this.resetForm('form')
        },

        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },

        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加电表信息'
        },

        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getElectricity(id).then(response => {
                this.form = response.data
                this.form.status = this.form.status + ''
                this.form.electricMeterMode = this.form.electricMeterMode + ''
                this.open = true
                this.title = '修改电表信息'
            })
        },
        // 更多
        handleCommand(command, row) {
            switch (command) {
                case 'handlePay':
                    this.handlePay(row)
                    break
                case 'handleSchedule':
                    this.handleSchedule(row)
                    break
                case 'handleReading':
                    this.handleReading(row)
                    break
                case 'handleSwitchStatus':
                    this.handleSwitchStatus(row)
                    break
                case 'handleDetail':
                    this.handleDetail(row)
                    break
                default:
                    break
            }
        },
        /** 明细操作 */
        handleDetail(row) {
            this.$router.push({
                path: '/electricity/detail',
                query: { row }
            })
        },
        /** 充值按钮操作 */
        handlePay(row) {
            this.$refs.payDig.open(row)
        },
        /** 定时操作 */
        handleSchedule(row) {
            this.$refs.scheduleDig.open(row)
        },
        /* 转移电表 */
        handleTransfer() {
            this.$refs.transferDig.open()
        },
        /** 抄表 */
        handleReading(row) {
            clearInterval(this.heartTime)
            let obj = {
                sn: row.sn,
                clientId: this.webClientId
            }
            this.loading = true
            this.isFirstHandle = true
            this.getTimer()
            readingElectricMeter(obj).then(res => {
                if (res) {
                    this.text = '抄表成功'
                    this.sendWebsocketMessage(this.webClientId)
                }
            }, error => {
                this.resetTime()
            })
        },
        /** 强制拉闸-解除拉闸 */
        handleSwitchStatus(row) {
            clearInterval(this.heartTime)
            let switchStatus
            this.getTimer()
            if (row.switchStatus === '0') {
                switchStatus = '1'
                this.text = '拉闸成功'
            } else {
                switchStatus = '0'
                this.text = '解除成功'
            }
            let obj = {
                sn: row.sn,
                clientId: this.webClientId,
                switchStatus
            }
            this.loading = true
            this.isFirstHandle = true
            forceoffElectricMeter(obj).then(res => {
                if (res) {
                    this.sendWebsocketMessage(this.webClientId)
                }
            }, error => {
                this.resetTime()
            })
        },
        sendWebsocketMessage(webClientId) {
            this.initWebSocket(webClientId)
        },
        // 初始化socket
        initWebSocket(webClientId) {
            if (this.readyStatus === 1) {
                console.log('存在连接')
                this.webSocketOnMessage()
            } else {
                //建立连接
                this.socketUrl = 'ws://8.129.223.218:16035/agriculture/ws/device?clientId=' + webClientId
                // 初始化 websocket
                this.websocket = new WebSocket(this.socketUrl)
                this.webSocketOnOpen()
                this.webSocketOnMessage()
                this.webSocketOnError()
                this.webSocketClose()
                // sendSocketHeart()
            }
        },
        // socket 打开连接
        webSocketOnOpen() {
            let that = this
            this.websocket.onopen = function(e) {
                that.isOpen = true
                console.log('开始连接', e)
                that.resetHeart()
                that.resetHeart()
            }
        },
        // socket 接收数据
        webSocketOnMessage() {
            let that = this
            this.websocket.onmessage = function(e) {
                console.log('收到socket消息', e.data)
                try {
                    let data = JSON.parse(e.data)
                    if (data.code === 200) {
                        that.loading = false
                        that.getList()
                        that.$message.success(that.text)
                        clearInterval(that.timer)
                    }
                } catch (e) {
                    console.log(e)
                }
            }
        },
        // socket 连接失败
        webSocketOnError() {
            let that = this
            this.websocket.onerror = function(e) {
                console.log('连接 websocket 失败', e)
                that.$message.error('操作失败')
                that.resetTime()
            }
        },
        // socket 断开链接
        webSocketClose() {
            let that = this
            this.websocket.onclose = function(e) {
                console.log('断开连接', e)
                that.readyStatus = 0
            }
        },
        // socket 重置心跳
        resetHeart() {
            this.socketHeart = 0
            this.socketError = 0
            clearInterval(this.heartTime)
            this.sendSocketHeart()
        },
        // socket心跳发送
        sendSocketHeart() {
            this.isFirstHandle = false
            console.log(this.websocket)
            this.readyStatus = this.websocket.readyState
            if (!this.isFirstHandle) {
                let that = this
                this.heartTime = setInterval(() => {
                    // 如果连接正常则发送心跳
                    if (that.websocket.readyState == 1) {
                        // if (socketHeart <= 30) {
                        console.log('心跳发送：', that.socketHeart)
                        that.websocket.send(
                            JSON.stringify({
                                type: 'heart'
                            })
                        )
                        that.socketHeart = that.socketHeart + 1
                    } else {
                        // 重连
                        that.reconnect()
                    }
                }, that.HeartTimeOut)
            }
        },
        // socket重连
        reconnect() {
            if (this.socketError <= 2) {
                clearInterval(this.heartTime)
                this.initWebSocket(this.socketUrl)
                this.socketError = this.socketError + 1
                console.log('socket重连', this.socketError)
            } else {
                console.log('重试次数已用完的逻辑', this.socketError)
                clearInterval(this.heartTime)
            }
        },
        getTimer() {
            console.log(111)
            let loadingTime = 5
            let that = this
            this.timer = setInterval(() => {
                if (loadingTime <= 0) {
                    that.resetTime()
                } else {
                    // loadingText.value = loadingTime+ 's'
                    --loadingTime
                }
            }, 1000)
        },
        // 重置
        resetTime() {
            clearInterval(this.heartTime)
            clearInterval(this.timer)
            // this.loading.close()
            this.loading = false
            this.$message.error('系统繁忙，请稍后再试')
        },
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateElectricity(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addElectricity(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },

        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除电表').then(function() {
                return delElectricity(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },

        handleExport() {
            this.download('system/card/export', {
                ...this.queryParams
            }, `card_${new Date().getTime()}.xlsx`)
        }
    }
}
</script>
